package com.zsd.android.apteventbus.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public class PhoneUtil {

    private static boolean mHaveRoot = false;

    /**
     * 检测app是否拥有Root权限
     *
     * @param packageCodePath
     * @return
     */
    public static boolean checkRoot(String packageCodePath) {
        Process process = null;
        BufferedReader br = null;
        String cmd = "ls -l " + packageCodePath;
        try {
            process = Runtime.getRuntime().exec(cmd);
            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String regx = "-rwxr[\\s\\S]+";
            MLog.i("sb = " + sb.toString());
            return Pattern.matches(regx, sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
            MLog.i("checkRoot error : " + e.getMessage());
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

    public static boolean checkRoot() {
        if (!mHaveRoot) {
            int ret = execRootCmdSilent("echo test"); // 通过执行测试命令来检测
            if (ret != -1) {
                mHaveRoot = true;
            }
        }
        return mHaveRoot;
    }

    /**
     * 执行adb命令，
     * 可用于获取Root权限："chmod 777 $packageCodePath"
     * packageCodePath = context.getPackageCodePath();
     *
     * @param cmd
     * @return
     */
    public static int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;
        Process process = null;

        try {
            process = Runtime.getRuntime().exec("/system/bin/sh");
            dos = new DataOutputStream(process.getOutputStream());

            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            process.waitFor();
            result = process.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
            MLog.i("execRootCmdSilent error : " + e.getMessage());
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
}
